package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.QueryPurchasesParams;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.act.game.Lucky;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.pay.GoogleBillHelper;
import org.chen.wordwave.pay.GoogleBillingListener;
import org.chen.wordwave.pay.GoogleBillingManager;
import org.chen.wordwave.tools.user.UserUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MemberCenter extends BaseActivity {
    private static final String TAG = "MemberCenter";
    private ImageView floatingGiftIcon;
    private TextView tvMembershipStatus, tvMembershipBenefits, tvCurrentPoints, tvDiscountedPoints;
    private Button btnRedeemPoints, btnSubscribe, btnManageSubscription;
    private UserInfo currentUser;
    private TextView tv_title;
    private RadioGroup radioGroupMembershipDuration;
    private RadioButton radioOneMonth, radioThreeMonths, radioOneYear;
    private int selectedDuration = -1;
    private int requiredPoints;
    private ImageView iv_goback;
    private ApiService apiService;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private GoogleBillHelper billProxy = new GoogleBillHelper();
    private GoogleBillingListenerImpl billingListenerImpl = new GoogleBillingListenerImpl();

    private static final String SUBS_MONTHLY = "vip_one_month";
    private static final String SUBS_QUARTERLY = "vip_quarterly";
    private static final String SUBS_YEARLY = "vip_yearly";

    private String selectedSubscriptionId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apiService = ApiClient.getClient(this).create(ApiService.class);
        GoogleBillingManager.getInstance().createClient(this);
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.member_center_act;
    }

    @Override
    public void init() {
        initViews();
        setupListeners();
        loadCurrentUser();
        checkMembershipStatus();
        displayMembershipBenefits();
        displayCurrentPoints();
        setupGiftAnimation();
    }

    private void initViews() {
        tvMembershipStatus = findViewById(R.id.tv_membership_status);
        tvMembershipBenefits = findViewById(R.id.tv_membership_benefits);
        btnRedeemPoints = findViewById(R.id.btn_redeem_points);
        btnSubscribe = findViewById(R.id.btn_subscribe);
        btnManageSubscription = findViewById(R.id.btn_manage_subscription);
        tv_title = findViewById(R.id.tv_title);
        iv_goback = findViewById(R.id.iv_goback);
        radioGroupMembershipDuration = findViewById(R.id.radio_group_membership_duration);
        radioOneMonth = findViewById(R.id.radio_one_month);
        tvDiscountedPoints = findViewById(R.id.tv_discounted_points);
        radioThreeMonths = findViewById(R.id.radio_three_months);
        radioOneYear = findViewById(R.id.radio_one_year);
        tvCurrentPoints = findViewById(R.id.tv_current_points);
        floatingGiftIcon = findViewById(R.id.floating_gift_icon);

        tv_title.setText(R.string.my_vip3);
        btnManageSubscription.setVisibility(View.GONE);
    }

    private void setupListeners() {
        radioGroupMembershipDuration.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_one_month) {
                selectedDuration = Calendar.MONTH;
                selectedSubscriptionId = SUBS_MONTHLY;
                requiredPoints = 1000;
            } else if (checkedId == R.id.radio_three_months) {
                selectedDuration = Calendar.MONTH * 3;
                selectedSubscriptionId = SUBS_QUARTERLY;
                requiredPoints = 2500;
            } else if (checkedId == R.id.radio_one_year) {
                selectedDuration = Calendar.YEAR;
                selectedSubscriptionId = SUBS_YEARLY;
                requiredPoints = 8000;
            }
            displayCurrentPoints();
        });

        btnRedeemPoints.setOnClickListener(v -> redeemPointsForMembership());
        btnSubscribe.setOnClickListener(v -> handleSubscribeClick());
        btnManageSubscription.setOnClickListener(v -> openSubscriptionManagementPage());
        iv_goback.setOnClickListener(v -> finish());
        floatingGiftIcon.setOnClickListener(v -> startActivity(new Intent(MemberCenter.this, Lucky.class)));
    }

    private void handleSubscribeClick() {
        if (selectedDuration == -1) {
            Toaster.show(getString(R.string.tips_vip));
            return;
        }
        if (currentUser.isMember()) {
            Toaster.show(getString(R.string.tips_vip_2));
            return;
        }

        Log.d(TAG, "Querying subscription with ID: " + selectedSubscriptionId);
        billProxy.querySubscriptionDetails(billingListenerImpl, selectedSubscriptionId);
    }

    private void openSubscriptionManagementPage() {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://play.google.com/store/account/subscriptions"));
            startActivity(intent);
        } catch (Exception e) {
            Toaster.show(getString(R.string.open_play_store_failed));
        }
    }

    private class GoogleBillingListenerImpl implements GoogleBillingListener {
        @Override
        public void onProductDetailsSus(List<ProductDetails> list) {
            if (null == list || list.isEmpty()) {
                Log.e(TAG, "没有查询到相关订阅产品");
                return;
            }
            billProxy.onOpenGooglePlay(this, MemberCenter.this, list.get(0));
        }

        @Override
        public void onPurchasesUpdated(BillingResult result, List<Purchase> purchases) {
            if (result.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                if (purchases != null) {
                    for (Purchase purchase : purchases) {
                        handlePurchase(purchase);
                    }
                } else {
                    updateMembershipToExpired();
                }
            }
        }
    }

    private void handlePurchase(Purchase purchase) {
        Log.d(TAG, "Handling purchase: " + purchase.getOrderId() +
                ", State: " + purchase.getPurchaseState() +
                ", Acknowledged: " + purchase.isAcknowledged());

        if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
            if (purchase.getProducts().contains(SUBS_MONTHLY) ||
                    purchase.getProducts().contains(SUBS_QUARTERLY) ||
                    purchase.getProducts().contains(SUBS_YEARLY)) {

                updateMembershipStatus(purchase);
            }
        } else if (purchase.getPurchaseState() == Purchase.PurchaseState.PENDING) {
            Log.d(TAG, "Subscription pending");
        } else {
            Log.w(TAG, "Purchase state: " + purchase.getPurchaseState());
            updateMembershipToExpired();
        }
    }

    private void updateMembershipStatus(Purchase purchase) {
        try {
            // 检查购买是否已经被确认过
            if (!purchase.isAcknowledged()) {
                // 确认购买
                AcknowledgePurchaseParams acknowledgePurchaseParams =
                        AcknowledgePurchaseParams.newBuilder()
                                .setPurchaseToken(purchase.getPurchaseToken())
                                .build();

                GoogleBillingManager.getInstance().getBillingClient()
                        .acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
                            @Override
                            public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) {
                                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                                    Log.d(TAG, "Purchase acknowledged successfully");
                                    // 确认成功后处理会员状态
                                    processMembershipUpdate(purchase);
                                } else {
                                    Log.e(TAG, "Failed to acknowledge purchase: " + billingResult.getDebugMessage());
                                    // 确认失败，但仍然处理会员状态（因为用户已经付款）
                                    processMembershipUpdate(purchase);
                                }
                            }
                        });
            } else {
                // 购买已经被确认过，直接处理会员状态
                Log.d(TAG, "Purchase already acknowledged");
                processMembershipUpdate(purchase);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in updateMembershipStatus", e);
        }
    }

    private void processMembershipUpdate(Purchase purchase) {
        try {
            long expiryTimeMillis = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(30);

            String productId = purchase.getProducts().get(0);
            if (productId.equals(SUBS_QUARTERLY)) {
                expiryTimeMillis = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(90);
            } else if (productId.equals(SUBS_YEARLY)) {
                expiryTimeMillis = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(365);
            }

            Date expiryDate = new Date(expiryTimeMillis);
            currentUser.setMember(true);
            currentUser.setMembershipType(2); // 设置为订阅会员
            currentUser.setMembershipExpiryDate(expiryDate);
            currentUser.save();

            runOnUiThread(() -> {
                updateUIAfterRedemption(expiryDate);
                btnManageSubscription.setVisibility(View.VISIBLE);
                btnSubscribe.setEnabled(false);
            });

            syncSubscriptionToServer();
        } catch (Exception e) {
            Log.e(TAG, "Error processing membership update", e);
        }
    }

    private void updateMembershipToExpired() {
        // 只有订阅会员才处理过期
        if (currentUser.getMembershipType() == 2) {
            currentUser.setMember(false);
            currentUser.setMembershipType(0);
            currentUser.setMembershipExpiryDate(null);
            currentUser.save();

            runOnUiThread(() -> {
                checkMembershipStatus();
                btnManageSubscription.setVisibility(View.GONE);
                btnSubscribe.setEnabled(true);
            });

            syncSubscriptionToServer();
        }
    }

    private void syncSubscriptionToServer() {
        SignIn signIn = new SignIn();
        signIn.setEmail(currentUser.getEmail());
        signIn.setMember(currentUser.isMember());
        signIn.setPoints(currentUser.getPoints());
        signIn.setMembershipExpiryDate(currentUser.getMembershipExpiryDate() != null ?
                currentUser.getMembershipExpiryDate().getTime() : 0);
        signIn.setMembershipType(currentUser.getMembershipType());

        syncToServer(signIn);
    }

    private void loadCurrentUser() {
        currentUser = UserUtils.getCurrentUser(getApplicationContext());
    }

    private void displayCurrentPoints() {
        int originalPoints = requiredPoints;
        int requiredPointsWithDiscount;
        String discountInfo = "";

        if (currentUser.isHasDiscountCoupon()) {
            tvDiscountedPoints.setVisibility(View.VISIBLE);
            requiredPointsWithDiscount = (int) (requiredPoints * currentUser.getDiscountRate());

            discountInfo = String.format(Locale.getDefault(),
                    getString(R.string.discount_info),
                    originalPoints,
                    requiredPointsWithDiscount,
                    currentUser.getDiscountRate() * 10);
        }

        tvDiscountedPoints.setText(discountInfo);
        tvCurrentPoints.setText(String.valueOf(currentUser.getPoints()));
    }

    @SuppressLint("SetTextI18n")
    private void checkMembershipStatus() {
        if (currentUser.isMember() && currentUser.getMembershipExpiryDate() != null) {
            Date currentDate = new Date();
            if (currentDate.after(currentUser.getMembershipExpiryDate())) {
                updateMembershipToExpired();
            } else {
                String formattedDate = dateFormat.format(currentUser.getMembershipExpiryDate());
                tvMembershipStatus.setText(getString(R.string.vip_time) + formattedDate);
                if (currentUser.getMembershipType() == 2){
                    btnManageSubscription.setVisibility(View.VISIBLE);
                    btnSubscribe.setEnabled(false);
                }
            }
        } else {
            tvMembershipStatus.setText(getString(R.string.no_vip));
            btnManageSubscription.setVisibility(View.GONE);
            btnSubscribe.setEnabled(true);
        }
    }

    private void displayMembershipBenefits() {
        tvMembershipBenefits.setText(getString(R.string.vip_content));
    }

    private void setupGiftAnimation() {
        floatingGiftIcon.setBackgroundResource(R.drawable.gift_animation);
        AnimationDrawable giftAnimation = (AnimationDrawable) floatingGiftIcon.getBackground();
        giftAnimation.start();
        floatingGiftIcon.bringToFront();
    }

    private void redeemPointsForMembership() {
        if (selectedDuration == -1) {
            Toaster.show(getString(R.string.tips_vip));
            return;
        }

        if (currentUser.isMember()) {
            Toaster.show(getString(R.string.tips_vip_2));
            return;
        }

        if (currentUser.isHasDiscountCoupon()) {
            requiredPoints = (int) (requiredPoints * currentUser.getDiscountRate());
        }

        if (currentUser.getPoints() >= requiredPoints) {
            processPointsRedemption();
        } else {
            showInsufficientPointsError();
        }
    }

    private void processPointsRedemption() {
        currentUser.setPoints(currentUser.getPoints() - requiredPoints);
        currentUser.setMember(true);
        currentUser.setMembershipType(1); // 设置为积分兑换会员
        Date membershipExpiryDate = getExpiryDate();
        currentUser.setMembershipExpiryDate(membershipExpiryDate);
        currentUser.setHasDiscountCoupon(false);
        currentUser.setDiscountRate(1.0);

        updateUIAfterRedemption(membershipExpiryDate);
        syncRedemptionToServer();
    }

    private Date getExpiryDate() {
        Calendar calendar = Calendar.getInstance();
        if (selectedDuration == Calendar.MONTH) {
            calendar.add(Calendar.MONTH, 1);
        } else if (selectedDuration == Calendar.MONTH * 3) {
            calendar.add(Calendar.MONTH, 3);
        } else if (selectedDuration == Calendar.YEAR) {
            calendar.add(Calendar.YEAR, 1);
        }
        return calendar.getTime();
    }

    private void updateUIAfterRedemption(Date expiryDate) {
        checkMembershipStatus();
        displayCurrentPoints();

        ToastParams toastParams = new ToastParams();
        toastParams.style = new CustomToastStyle(R.layout.success);
        toastParams.text = getString(R.string.success_vip) + dateFormat.format(expiryDate);
        Toaster.show(toastParams);
    }

    private void showInsufficientPointsError() {
        ToastParams toastParams = new ToastParams();
        toastParams.style = new CustomToastStyle(R.layout.error);
        toastParams.text = getString(R.string.failed_vip);
        Toaster.show(toastParams);
    }

    private void syncRedemptionToServer() {
        SignIn signIn = new SignIn();
        signIn.setEmail(currentUser.getEmail());
        signIn.setPoints(currentUser.getPoints());
        signIn.setMembershipExpiryDate(currentUser.getMembershipExpiryDate().getTime());
        signIn.setMember(currentUser.isMember());
        signIn.setHasDiscountCoupon(currentUser.isHasDiscountCoupon());
        signIn.setDiscountRate(currentUser.getDiscountRate());
        signIn.setMembershipType(currentUser.getMembershipType());
        syncToServer(signIn);
    }

    private void syncToServer(SignIn signIn) {
        new Thread(() -> {
            runOnUiThread(() -> {
                apiService.gift(signIn).enqueue(new Callback<SignIn>() {
                    @Override
                    public void onResponse(@NonNull Call<SignIn> call, @NonNull Response<SignIn> response) {

                    }

                    @Override
                    public void onFailure(@NonNull Call<SignIn> call, @NonNull Throwable t) {
                        Log.e(TAG, "Sync failed", t);
                    }
                });
            });
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadCurrentUser();
        checkMembershipStatus();
        displayCurrentPoints();

        if (GoogleBillingManager.getInstance().isReady()) {
            BillingClient billingClient = GoogleBillingManager.getInstance().getBillingClient();
            billingClient.queryPurchasesAsync(
                    QueryPurchasesParams.newBuilder()
                            .setProductType(BillingClient.ProductType.SUBS)
                            .build(),
                    (billingResult, purchases) -> {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                            if (purchases.isEmpty()) {
                                // 没有任何订阅记录
                                updateMembershipToExpired();
                            } else {
                                boolean hasActiveSubscription = false;
                                for (Purchase purchase : purchases) {
                                    if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                        checkSubscriptionStatus(purchase);
                                        // 检查是否需要确认购买
                                        if (!purchase.isAcknowledged()) {
                                            handlePurchase(purchase);
                                        } else if (purchase.isAutoRenewing()) {
                                            hasActiveSubscription = true;
                                            handlePurchase(purchase);
                                            break;
                                        }
                                    }
                                }
                                if (!hasActiveSubscription) {
                                    updateMembershipToExpired();
                                }
                            }
                        } else {
                            Log.e(TAG, "Failed to query purchases: " + billingResult.getDebugMessage());
                        }
                    }
            );
        } else {
            Log.e(TAG, "Billing client not ready");
            GoogleBillingManager.getInstance().createClient(this);
        }
    }

    private void checkSubscriptionStatus(Purchase purchase) {
        if (currentUser.getMembershipType() == 2) {
            // 检查订阅是否已经被取消
            boolean isSubscriptionActive = purchase.isAutoRenewing();
            // 检查订阅是否已经过期
            boolean isExpired = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(30) < System.currentTimeMillis();

            // 根据订阅类型调整过期时间
            if (purchase.getProducts().contains(SUBS_QUARTERLY)) {
                isExpired = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(90) < System.currentTimeMillis();
            } else if (purchase.getProducts().contains(SUBS_YEARLY)) {
                isExpired = purchase.getPurchaseTime() + TimeUnit.DAYS.toMillis(365) < System.currentTimeMillis();
            }

            if (!isSubscriptionActive || isExpired) {
                updateMembershipToExpired();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Google Play计费连接
        GoogleBillingManager.getInstance().endConn();
    }
}